package com.example.filedownandjson.controller.music;

import com.example.filedownandjson.controller.music.bean.JsonResponse;
import com.example.filedownandjson.controller.music.bean.MusicItem;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@RestController
public class MusicList {
    @RequestMapping("/musicList")
    public JsonResponse<List<MusicItem>> musicList() {
        List<MusicItem> musicItemList = new ArrayList<>();
        File file = new File("D:\\Music");
        File[] fileLists = file.listFiles();
        for (int i = 0; i < fileLists.length; i++) {
            File fileItem = fileLists[i];
            String fileName = fileItem.getName();
            if (fileName.endsWith(".flac")) {
                int nameIndex = fileName.indexOf(".flac");
                String name = fileName.substring(0, nameIndex);

                MusicItem musicItem = new MusicItem();
                musicItem.setName(name);
                musicItem.setType("flac");
                musicItem.setPath("http://10.10.110.240:8082/downloadLocal?fileName=" + URLEncoder.encode(musicItem.getName(), StandardCharsets.UTF_8) + "&type=flac" + "&mimeType=" + URLEncoder.encode("audio/flac", StandardCharsets.UTF_8));
                musicItem.setLrcPath("http://10.10.110.240:8082/downloadLocal?fileName=" + URLEncoder.encode(musicItem.getName(), StandardCharsets.UTF_8) + "&type=lrc" + "&mimeType=" + URLEncoder.encode("application/octet-stream", StandardCharsets.UTF_8));
                musicItemList.add(musicItem);
            }
        }
        JsonResponse<List<MusicItem>> response = new JsonResponse<>();
        response.setCode(200);
        response.setMessage("ok");
        response.setData(musicItemList);
        return response;
    }
}
